package com.sykuku.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sykuku.common.R;
import com.sykuku.dao.DishMapper;
import com.sykuku.dto.DishDto;
import com.sykuku.pojo.Category;
import com.sykuku.pojo.Dish;
import com.sykuku.pojo.DishFlavor;
import com.sykuku.service.CategoryService;
import com.sykuku.service.DishFlavorService;
import com.sykuku.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @CacheEvict(value = "dishDto",allEntries = true)//清除dishDto名称下,所有的缓存数据
    public R<String> add(@RequestBody DishDto dishDto) {

        log.info("用户添加菜品分类{}", dishDto);

        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }


    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {
        log.info("用户进入菜品管理分页查询数据为:{}{}{}", page, pageSize, name);
        //自己写的sql方法
        //Page<DishDto> dishDtoPage = dishService.dishPage(page, pageSize, name);

        Page<Dish> dishpage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);


        dishService.page(dishpage, lqw);
        //正常查询单表查询的属性

        Page<DishDto> dishDtoPage = new Page<>();

        //属性拷贝 records是page<dish>数据的容器对象 要排除dish所有对象 因为拷贝不上 小转大无法转
        BeanUtils.copyProperties(dishpage, dishDtoPage, "records");

        //获取dish的所有属性对象进行赋值操作  get返回值是一个list
        List<Dish> records = dishpage.getRecords();
        //循环遍历每一个dish对象操作数据

        //创建一个储存Dto的容器
        ArrayList<DishDto> list = new ArrayList<>();

        records.forEach((dish) -> {
            //创建一个dto对象 并拷贝排除的dish属性
            DishDto dishDto = new DishDto();
            //把每一个dish对象拷贝到dto中
            BeanUtils.copyProperties(dish, dishDto);
            //获取每个对象的分类id值
            Long categoryId = dish.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                //获取分类对象的品类名称
                String categoryName = category.getName();
                //设置dto中的品类名称
                dishDto.setCategoryName(categoryName);
            }
            list.add(dishDto);
            //return dishDto;
        });
        //get的方法返回值是list对象
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    ;
    //菜品管理里面的修改回显菜品的信息
    @GetMapping("/{id}")

    public R<DishDto> selectById(@PathVariable Long id) {
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    ;
    //修改菜品信息
    @PutMapping
    @CacheEvict(value = "dishDto",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto){

        dishService.updateWithFlavor(dishDto);
        return R.success("成功");
    };

    //菜品分类的回显 已通过代码实现
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        List<DishDto> list = null;

        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844391040167938_1

        list = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(list != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(list);
        }

        log.info("用户新增套餐,新增套餐中的添加菜品回显功能{}",dish);
        //查询出dish的所有信息
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        lqw.eq(Dish::getStatus,1);
        //添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> DishList = dishService.list(lqw);

        //用dishdto的finalList接
        List<DishDto> finalList = new ArrayList<>();
        //循环Dish信息放入dishDto中

        DishList.forEach((dish1 ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1,dishDto);

            //查询Category表的分类名称
            Category category = categoryService.getById(dish.getCategoryId());
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //根据dishid查询口味表中的list对象
            //SQL:select * from dish_flavor where dish_id = ?
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dish1.getId());

            List<DishFlavor> flavors = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(flavors);
            finalList.add(dishDto);

        } ));
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,finalList,60, TimeUnit.MINUTES);

        return R.success(finalList);
    }

    @PostMapping("/status/{type}")
    @CacheEvict(value = "dishDto",allEntries = true)
    public R<String> staTop(@PathVariable Integer type,@RequestParam("ids")List<Long> ids){
        log.info("用户开始启停售操作是{}ids{}",type,ids);
        LambdaUpdateWrapper<Dish> luw = new LambdaUpdateWrapper<>();
        luw.set(Dish::getStatus,type);
        luw.in(Dish::getId,ids);
        dishService.update(luw);
        return R.success("修改成功");

    }






}